// src/components/ApiDebugPanel.jsx
import { useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faXmark, faPlay, faSpinner } from '@fortawesome/free-solid-svg-icons';

const ApiDebugPanel = ({ workflows, workflowId, nodes, onClose, onSaveWorkflow }) => {
  const [response, setResponse] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const currentWorkflow = workflows.find(w => w.id === workflowId);

  // 自动收集输入节点数据
  const inputNodes = nodes.filter(n => n.type === 'inputNode');
  const defaultInputs = inputNodes.reduce((acc, node) => {
    try {
      acc[node.id] = JSON.parse(node.data.content);
    } catch {
      acc[node.id] = node.data.content;
    }
    return acc;
  }, {});

  const [inputData, setInputData] = useState(defaultInputs);

  // 处理API调用
  const handleExecute = async () => {
    if (!workflowId) {
      setError('请先保存工作流');
    //   alert('请先保存工作流');
      return;
    }
    setIsLoading(true);
    setError(null);
    await onSaveWorkflow(currentWorkflow.name, 'current');
    try {
      const res = await fetch(
        `http://localhost:8001/api/workflows/${workflowId}/execute-sync/`,
        {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(inputData),
        }
      );

      if (!res.ok) throw new Error(`请求失败: ${res.statusText}`);
      const data = await res.json();
      setResponse(data);
    } catch (err) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="fixed inset-y-0 right-0 w-96 bg-white shadow-xl z-[1000] flex flex-col">
      {/* 头部 */}
      <div className="p-4 border-b flex justify-between items-center">
        <h2 className="text-lg font-semibold">API调试</h2>
        <button onClick={onClose} className="text-gray-500 hover:text-gray-700">
          <FontAwesomeIcon icon={faXmark} size="lg" />
        </button>
      </div>

      {/* 内容区域 */}
      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        <div>
          <h3 className="text-sm font-medium mb-2">API端点</h3>
          <div className="bg-gray-100 p-3 rounded text-sm font-mono break-all">
            POST http://localhost:8001/api/workflows/{workflowId || ':workflow_id'}/execute-sync/
          </div>
        </div>

        <div>
          <h3 className="text-sm font-medium mb-2">请求参数</h3>
          {/* {inputNodes[0].id} */}
          {inputNodes.length > 0 ? (
            <div className="space-y-3">
              {inputNodes.map(node => (
                <div key={node.id}>
                  <label className="text-xs text-gray-600 block mb-1">
                    {node.data.label} ({node.id})
                  </label>
                  <textarea
                    type="text"
                    value={ 
                      typeof inputData[node.id] === 'object' 
                        ? JSON.stringify(inputData[node.id], null, 2)
                        : inputData[node.id] ?? ''
                    }
                    onChange={(e) => {
                      try {
                        const parsed = JSON.parse(e.target.value);
                        setInputData(prev => ({ ...prev, [node.id]: parsed }));
                      } catch {
                        setInputData(prev => ({ ...prev, [node.id]: e.target.value }));
                      }
                    }}
                    className="w-full h-32 px-2 py-1 border rounded text-sm"
                  />
                </div>
              ))}
            </div>
          ) : (
            <div className="text-gray-500 text-sm">没有找到输入节点</div>
          )}
          
        </div>

        <div>
          <button
            onClick={handleExecute}
            // disabled={isLoading || !workflowId}
            className={`w-full py-2 rounded flex items-center justify-center gap-2 ${
              isLoading 
                ? 'bg-gray-400 cursor-not-allowed' 
                : 'bg-blue-500 hover:bg-blue-600 text-white'
            }`}
          >
            {isLoading ? (
              <>
                <FontAwesomeIcon icon={faSpinner} className="animate-spin" />
                <span>执行中...</span>
              </>
            ) : (
              <>
                <FontAwesomeIcon icon={faPlay} />
                <span>执行请求</span>
              </>
            )}
          </button>
        </div>

        {error && (
          <div className="p-3 bg-red-50 text-red-600 rounded text-sm">
            <strong>错误:</strong> {error}
          </div>
        )}

        {response && (
          <div>
            <h3 className="text-sm font-medium mb-2">响应结果</h3>
            <pre className="bg-gray-100 p-3 rounded text-sm overflow-x-auto max-h-64">
              {JSON.stringify(response, null, 2)}
            </pre>
          </div>
        )}
      </div>

      {/* 文档说明 */}
      <div className="p-4 border-t text-sm">
        <h3 className="font-medium mb-2">使用说明</h3>
        <ul className="list-disc pl-4 space-y-2 text-gray-600">
          <li>请确保工作流包含至少一个输入节点和输出节点</li>
          <li>请求参数需要与输入节点ID对应</li>
          <li>返回输出节点的处理结果</li>
          <li>支持JSON格式的嵌套参数</li>
        </ul>
      </div>
    </div>
  );
};

export default ApiDebugPanel;